package com.xiguaji.tiktok.v1.ins.brand.service;

import cn.hutool.core.date.DateUtil;
import com.xiguaji.boot.toolkit.elasticsearch.RestClientHelper;
import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.utils.ESUtil;
import com.xiguaji.tiktok.v1.ins.brand.dto.*;
import com.xiguaji.tiktok.v1.ins.brand.model.*;
import com.xiguaji.tiktok.v1.ins.brand.repository.*;
import com.xiguaji.tiktok.v1.ins.config.InsConfig;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class InsBrandService {
    @Autowired
    CommonBrandRepository commonBrandRepository;
    @Autowired
    InsStBrandGenderRepository insStBrandGenderRepository;
    @Autowired
    InsStBrandGenerationRepository insStBrandGenerationRepository;
    @Autowired
    InsStBrandLanguageRepository insStBrandLanguageRepository;
    @Autowired
    InsStBrandNationRepository insStBrandNationRepository;
    @Autowired
    InsStBrandRaceRepository insStBrandRaceRepository;
    @Autowired
    InsConfig insConfig;

    private final int FANS_DATA_SIZE = 10;

    private final int [] days = new int []{7,15,30};

    public Page<InsBrandResp> getPage(InsBrandSearchRes insBrandSearchRes){
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.rangeQuery("influencer").gt(0));
        if(!StringUtils.isEmpty(insBrandSearchRes.getName())){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("enName","*"+insBrandSearchRes.getName().toLowerCase()+"*"));
        }

        if(!StringUtils.isEmpty(insBrandSearchRes.getCategory())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("categoryName",insBrandSearchRes.getCategory()));

        }

        String sortStr = "mediaCount";
        switch (insBrandSearchRes.getSort()){
            case 1:
                sortStr = "likes";
                break;
            case 2:
                sortStr = "reviews";
                break;
            case 3:
                sortStr = "engagements";
                break;
        }


        Page<InsBrandResp> page = RestClientHelper.page(InsBrandResp.class, ESUtil.INS_BRAND_INDEX,boolQueryBuilder,insBrandSearchRes.getPage(),insBrandSearchRes.getPageSize(),1000,sortStr, SortOrder.DESC);

        page.getList().forEach( brandResp -> {
            String logo = commonBrandRepository.findCommonBrandMoreFansBloggerPic(brandResp.getId());
            brandResp.setLogo(logo);
        });

        return page;
    }

    /**
     * 获取品牌下的博主UID拼接串
     * @return
     */
    public List<Long> getBrandUserId(int brandId){
        return commonBrandRepository.findUidByBrandId(brandId);
    }

    /**
     * 获取品牌下博主的username拼接串
     * @param brandId
     * @return
     */
    public String getBrandUserUsernameStr(int brandId){
        return commonBrandRepository.findUsernameByBrandId(brandId);
    }

    /**
     * 统计品牌下的帖子信息
     * @return
     */
    public MediaCountResp getBrandStMedia(int brandId,int dayType){
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandMediaCount(brandId,times[0],times[1]);
    }

    /**
     * 统计品牌下的帖子发文走趋
     * @param brandId
     * @param dayType
     * @return
     */
    public List<MediaCountResp> getBrandStMediaTrend(int brandId, int dayType){
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandMediaCountGroupDay(brandId,times[0],times[1]);
    }

    /**
     * 品牌下的帖子分页
     * @param brandMediaSearchRes
     * @return
     */
    /*public Page<MediaInfoResp> getBrandMediaPage(BrandMediaSearchRes brandMediaSearchRes){
        List<Long> uids = getBrandUserId(brandMediaSearchRes.getBrandId());
        if(uids.size() == 0){
            return null;
        }
        String usernameStr = getBrandUserUsernameStr(brandMediaSearchRes.getBrandId());
        Long [] times = lastStTime(brandMediaSearchRes.getBrandId(),brandMediaSearchRes.getDayType());
        return commonBrandRepository.getBrandMediaPage(brandMediaSearchRes, uids,usernameStr,times[0],times[1]);
    }*/

    public Page<MediaInfoResp> getBrandMediaPage(BrandMediaSearchRes brandMediaSearchRes){
        Long [] times = lastStTime(brandMediaSearchRes.getBrandId(),brandMediaSearchRes.getDayType());
        return commonBrandRepository.getBrandMediaPage(brandMediaSearchRes,times[0],times[1]);
    }

    public Page<MediaInfoResp> getBrandBloggerMediaPage(BrandMediaSearchRes brandMediaSearchRes){
        return commonBrandRepository.getBrandMediaPage(brandMediaSearchRes,System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600,System.currentTimeMillis() / 1000);
    }

    /**
     * 品牌下的商品帖子信息统计
     * @param brandId
     * @param dayType
     * @return
     */
    public MediaCountResp getBrandProductSt(int brandId, int dayType){
        List<Long> uids = getBrandUserId(brandId);
        if(uids.size() == 0){
            return null;
        }
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandMediaCountByProduct(uids,times[0],times[1]);
    }

    /**
     * 统计品牌下商品的帖子发文走趋
     * @param brandId
     * @param dayType
     * @return
     */
    public List<MediaCountResp> getBrandProductStTrend(int brandId, int dayType){
        List<Long> uids = getBrandUserId(brandId);
        if(uids.size() == 0){
            return null;
        }
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandProductMediaCountByGroupDay(uids,times[0],times[1]);
    }

    /**
     * 统计品牌下商品分类
     * @param brandId
     * @param dayType
     * @return
     */
    public List<ProductCategoryCount> getBrandProductCategoryCount(int brandId, int dayType){
        List<Long> uids = getBrandUserId(brandId);
        if(uids.size() == 0){
            return null;
        }
        Long [] times = lastStTime(brandId,dayType);
        List<ProductCategoryCount> categoryCounts = commonBrandRepository.findBrandMediaCountByGroupProductCategory(uids,times[0],times[1]);
        int allCount = 0;

        for (ProductCategoryCount productCategoryCount : categoryCounts) {
            allCount +=productCategoryCount.getCount();
        }
        if(allCount > 0){
            ProductCategoryCount productCategoryCount = new ProductCategoryCount();
            productCategoryCount.setCategory("ALL");
            productCategoryCount.setCount(allCount);
            categoryCounts.add(0,productCategoryCount);
        }
        categoryCounts.removeIf(i -> io.micrometer.core.instrument.util.StringUtils.isEmpty(i.getCategory()));
        return categoryCounts;
    }

    /**
     * 品牌下商品列表
     * @param brandMediaSearchRes
     * @return
     */
    public Page<ProductInfoResp> getBrandProductPage(BrandMediaSearchRes brandMediaSearchRes){
        List<Long> uids = getBrandUserId(brandMediaSearchRes.getBrandId());
        if(uids.size() == 0){
            return new Page<>(null,brandMediaSearchRes.getPage(),brandMediaSearchRes.getPageSize(),0,0);
        }
        Long [] times = lastStTime(brandMediaSearchRes.getBrandId(),brandMediaSearchRes.getDayType());
        return commonBrandRepository.getBrandProductPage(brandMediaSearchRes.getPage(),brandMediaSearchRes.getPageSize(),uids,brandMediaSearchRes.getCategory(),times[0],times[1]);
    }

    public CommonBrand getBrandByName(String name){
        CommonBrand commonBrand = commonBrandRepository.findByEnName(name);
        commonBrand.setLogo(commonBrandRepository.findCommonBrandMoreFansBloggerPic(commonBrand.getId()));
        return commonBrand;
    }


    private Long [] lastStTime(int bid,int dayType) {
       /* Long endTime = commonBrandRepository.lastStTime(bid);
        if(null == endTime || 0 == endTime){
            endTime = DateUtil.currentSeconds();
        }*/
        Long endTime = DateUtil.currentSeconds();
        Long startTime = endTime - days[dayType]*24*3600;
        Long [] times = new Long[]{startTime,endTime};
        return times;
    }


    /**
     * 品牌账户概览
     * @param brandId
     * @param dayType
     * @return
     */
    public InsBrandAccountOverviewResp getBrandAccountOverview(int brandId, int dayType){
        // 查询时间范围
        Long [] times = lastStTime(brandId,dayType);
        InsBrandAccountOverviewResp insBrandAccountOverviewResp = commonBrandRepository.findBrandAccountStMedia(brandId,times[0],times[1]);
        if(null == insBrandAccountOverviewResp){
            insBrandAccountOverviewResp = new InsBrandAccountOverviewResp();
        }
        return insBrandAccountOverviewResp;
    }

    /**
     * 品牌账户商业分类
     * @param brandId
     * @return
     */
    public List<InsBrandAccountCategory> getBrandAccountIndustry(int brandId){
        List<InsBrandAccountCategory> insBrandAccountCategories = commonBrandRepository.findBrandAccountIndustry(brandId);
        if(insBrandAccountCategories == null){
            insBrandAccountCategories = new ArrayList<>();
        }
        return insBrandAccountCategories;
    }

    /**
     * 品牌账户粉丝级别
     * @param brandId
     * @return
     */
    public InsBrandAccountFollowerSizeResp getBrandAccountFollowerSize(int brandId){
        InsBrandAccountFollowerSizeResp insBrandAccountFollowerSizeResp = new InsBrandAccountFollowerSizeResp();
        List<InsBrandAccountFollowerSize> insBrandAccountFollowerSizes = commonBrandRepository.findBrandAccountFollowerSize(brandId);
        if(insBrandAccountFollowerSizes != null && !insBrandAccountFollowerSizes.isEmpty()){
            long sum = 0;
            for(InsBrandAccountFollowerSize insBrandAccountFollowerSize : insBrandAccountFollowerSizes){
                if(insBrandAccountFollowerSize != null){
                    sum += insBrandAccountFollowerSize.getFollowerCount();
                }
            }
            insBrandAccountFollowerSizeResp.setFollowerCount(sum);
        }else{
            insBrandAccountFollowerSizes = new ArrayList<>();
        }
        insBrandAccountFollowerSizeResp.setInsBrandAccountFollowerSizes(insBrandAccountFollowerSizes);
        return insBrandAccountFollowerSizeResp;
    }

    /**
     * 品牌账户列表
     * @param brandId
     * @param dayType
     * @param page
     * @param pageSize
     * @return
     */
    public Page<InsBrandAccountInfo> getBrandAccountList(int brandId, int dayType,int page,int pageSize){
        // 查询时间范围
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandAccountPage(brandId,times[0],times[1],page,pageSize);
    }

    /**
     * 品牌达人分析-统计
     * @param brandId
     * @param dayType
     * @return
     */
    public MediaCountResp getBrandAdInfluencerCount(int brandId,int dayType){
        // 查询时间范围
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandInfluencerCount(brandId,false,times[0],times[1]);
    }

    /**
     * 获取品牌达人分析周走趋
     * @param brandId
     * @param dayType
     * @return
     */
    public List<PartnerWeekDayCountResp> getBrandAdInfluencerOfWeekDay(int brandId,int dayType){
        // 查询时间范围
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.findBrandAdBloggerOfWeekDay(brandId,times[0],times[1]);
    }

    /**
     * 获取品牌达人列表
     * @param brandId
     * @param dayType
     * @param page
     * @param pageSize
     * @return
     */
    public Page<BloggerInfoResp> getAdInfluencerPage(int brandId, int dayType,int page,int pageSize){
        // 查询时间范围
        Long [] times = lastStTime(brandId,dayType);
        return commonBrandRepository.getInfluencerPage(page,pageSize,brandId,false,times[0],times[1]);
    }

    /**
     * 品牌粉丝年龄性别占比
     * @param bid
     * @return
     */
    public BrandGenderResp getBrandFansGender(int bid){
        return insStBrandGenderRepository.findByBid(bid);
    }

    /**
     * 品牌粉丝年龄段
     * @param bid
     * @return
     */
    public List<InsStBrandGeneration> getBrandFansGenerations(int bid){
        return insStBrandGenerationRepository.findByBid(bid,FANS_DATA_SIZE);
    }

    /**
     * 品牌粉丝国家分布
     * @param bid
     * @return
     */
    public List<InsStBrandNation> getBrandFansNations(int bid){
        return insStBrandNationRepository.findByBid(bid,FANS_DATA_SIZE);
    }

    /**
     * 品牌粉丝语言分布
     * @param bid
     * @return
     */
    public List<InsStBrandLanguage> getBrandFansLanguages(int bid){
        return insStBrandLanguageRepository.findByBid(bid,FANS_DATA_SIZE);
    }

    /**
     * 品牌粉丝人种分布
     * @param bid
     * @return
     */
    public List<InsStBrandRace> getBrandFansRaces(int bid){
        return insStBrandRaceRepository.findByBid(bid,FANS_DATA_SIZE);
    }
}
